package com.chinacoal.microservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.chinacoal.microservice.mapper.*;
import com.chinacoal.microservice.pojo.*;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.CurrencyService;
import com.chinacoal.microservice.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author zhuliang
 * @version V1.0
 * @Description: 通用接口-后端实现类
 * @date 2020-11-17 17：58
 */
@Service
@Slf4j
public class CurrencyServiceImpl implements CurrencyService {

    @Autowired
    private CcmsSmartleasingAreaMapper smartleasingAreaMapper;

    @Autowired
    private CcmsSmartleasingBasicdataMapper basicdataMapper;

    @Autowired
    private BasicConfiguration basicConfiguration;

    @Autowired
    private CcmsSmartleasingDeviceManagementMapper deviceManagementMapper;

    @Autowired
    private CcmsSmartleasingMessageMapper messageMapper;

    @Autowired
    private CcmsSmartleasingBuildingMapper buildingMapper;

    @Autowired
    private CcmsSmartleasingHouseTypeMapper houseTypeMapper;

    @Autowired
    private CcmsSmartleasingTaxRateTemplateMapper taxRateTemplateMapper;

    @Autowired
    private CcmsSmartleasingRoomMapper roomMapper;

    @Autowired
    private CcmsSmartleasingCoefficientTemplateMapper coefficientTemplateMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    private static String[] yundingCommonAlarms = new String[]{ "installerSubmit","deviceInstall","deviceUninstall","lockOfflineAlarm","clearLockOfflineAlarm"
    };

    private static String[] yundingGatewayAlarms = new String[]{
            "centerOfflineAlarm","clearCenterOfflineAlarm"
    };

    private  static  String[] yundingLockAlarms = new String[]{ "batteryAlarm", "clearBatteryAlarm", "brokenAlarm", "wrongPwdAlarm", "lockerOpenAlarm","lockOpenHistoryAlarm", "batteryAsync", "pwdUpdateLocal"};

    private static String[] yundingEleMeterAlarms = new String[]{
            "elemeterPowerAsync","elemeterHistory","elemeterOvercomeAmount","pwdLostLocal","elemeterOvercomeCapacity","elemeterLocalClose","elemeterTransError","elemeterPowerHisAsync"
    };

    private static String[] yundingWaterMeterAlarms = new String[]{
            "deviceReplace","waterGatewayOfflineAlarm","waterGatewayOnlineAlarm","watermeterAmountAsync","watermeterOvercomeAmount"
    };

    /**
     * @Description: 中台登录接口
     * @author zhuliang
     * @date 2020/11/17 18:07
     */
    @Override
    public Result getLoginPerson(String token, Currency currency) {
        //将登录人信息放入redis中,并设置1小时的过期时间
        String signature = JWT.decode(token).getSignature();

        //查询登录人的权限类型
        String permissionType = basicdataMapper.getPermissionType(currency.getJurisdiction());

        //判断权限类型
        String property = "";
        String managementOffice = "";
        if ("003".equals(permissionType)) {
            property = currency.getJurisdiction();
        }else if ("016".equals(permissionType)) {
            managementOffice = currency.getJurisdiction();
        }else {
            log.error(CodeMsg.PERMISSION_DATE_EXCEPTION.toString() + "-->" + currency);
            return Result.error(CodeMsg.PERMISSION_DATE_EXCEPTION);
        }

        currency.setProperty(property);
        currency.setManagementOffice(managementOffice);
        currency.setAuthorityNumber(permissionType);

        redisTemplate.opsForValue().set("ccms:" + signature, currency, 1, TimeUnit.HOURS);

        return Result.success();
    }

    /**
     * @Description: 总登录接口
     * @author zhuliang
     * @date 2021/1/25 11:05
     */
    @Override
    public Result<String> adminLogin(Currency currency) {
        //获取数据库的账号信息
        List<CcmsSmartleasingBasicdata> basicdatas = basicdataMapper.getAllByTwoId(currency.getUserName(), null);

        //兼容性处理
        if (0 == basicdatas.size()) {
            log.error(CodeMsg.INCORRECT_USERNAME_OR_PASSWORD.toString() + "-->账号：" + currency.getUserName());
            return Result.error(CodeMsg.INCORRECT_USERNAME_OR_PASSWORD);
        }

        //获取第一个账号
        CcmsSmartleasingBasicdata basicdata = basicdatas.get(0);

        //判断密码是否一致
        if (!MD5Utils.getSaltverifyMD5(currency.getPassWord(), basicdata.getItemName())) {
            log.error(CodeMsg.INCORRECT_USERNAME_OR_PASSWORD.toString() + "-->账号：" + currency.getUserName() + "-->密码：" + currency.getPassWord());
            return Result.error(CodeMsg.INCORRECT_USERNAME_OR_PASSWORD);
        }

        //生成token
        String token = OrderNumberUtil.sign(currency.getUserName());

        //完善数据
        currency.setPassWord("");
        currency.setLoginId(0000);
        currency.setAuthorityNumber("");
        currency.setJurisdiction("");
        currency.setProperty("");
        currency.setManagementOffice("");
        currency.setLoginName("本系统管理员");
        currency.setToken(JWT.decode(token).getSignature());

        redisTemplate.opsForValue().set("ccms:" + JWT.decode(token).getSignature(), currency, 1, TimeUnit.HOURS);

        return Result.success(token);
    }

    /**
     * @Description: 根据对应的父类id查询对应的子类信息（省，市，区，街道）
     * @author zhuliang
     * @date 2020/11/19 9:16
     */
    @Override
    public Result<List<CcmsSmartleasingArea>> getParentIdList(Integer parentid) {
        //通过父类id查询子类信息
        List<CcmsSmartleasingArea> parentidList = smartleasingAreaMapper.getParentidList(parentid);

        return Result.success(parentidList);
    }

    /**
     * @Description: 查询楼宇模块所有的下拉框数据
     * @author zhuliang
     * @date 2020/11/30 20:49
     */
    @Override
    public Result<CcmsSmartleasingBasicdata> getAllByBuilding(String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //判断权限
        List<CcmsSmartleasingBasicdata> propertyCompanyList = null;
        if ("003".equals(currency.getAuthorityNumber()) || "".equals(currency.getAuthorityNumber())) {
            //查询所有的物业公司
            propertyCompanyList = basicdataMapper.getAllByOneId("003", currency.getProperty());
        } else if ("016".equals(currency.getAuthorityNumber())) {
            //查询所有的物业公司
            propertyCompanyList = basicdataMapper.getTwoByOne("003", currency.getManagementOffice());
        }

        //查询所有的所属区域信息
        List<CcmsSmartleasingBasicdata> regionList = basicdataMapper.getAllByOneId("001", null);

        //查询所有的房源类型信息
        List<CcmsSmartleasingBasicdata> housingSourceTypeList = basicdataMapper.getAllByOneId("002", null);

        //查询所有的权利人
        List<CcmsSmartleasingBasicdata> obligeeList = basicdataMapper.getAllByOneId("005", null);

        //写入返回值
        CcmsSmartleasingBasicdata basicdata = new CcmsSmartleasingBasicdata();
        basicdata.setRegionList(regionList);
        basicdata.setHousingSourceTypeList(housingSourceTypeList);
        basicdata.setObligeeList(obligeeList);
        basicdata.setPropertyCompanyList(propertyCompanyList);

        return Result.success(basicdata);
    }

    /**
     * @Description: 根据一级关联id查询二级信息
     * @author zhuliang
     * @date 2020/11/30 20:49
     */
    @Override
    public Result<List<CcmsSmartleasingBasicdata>> getAllByTwo(String id, String token) {
        //查询类型
        String permissionType = basicdataMapper.getPermissionType(id);
        List<CcmsSmartleasingBasicdata> basicdata = null;

        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        String tk = null;
        if (null == currency) {

            tk = (String) redisTemplate.opsForValue().get("wechat:" + JWT.decode(token).getClaim("phone").asString());

            if (null == tk || "".equals(tk) || "null".equals(tk)) {
                currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
            } else {

                basicdata = basicdataMapper.getAllByTwoId(id, null);
                return Result.success(basicdata);
            }
        }

        if ("003".equals(currency.getAuthorityNumber()) && "003".equals(permissionType)) {

            //判断是否有权限
            if (!currency.getProperty().equals(id)) {
                log.error(CodeMsg.NO_PRIVILEGES.toString() + "-->" + id);
                return Result.error(CodeMsg.NO_PRIVILEGES);
            }

            basicdata = basicdataMapper.getAllByTwoId(id, null);
        } else if ("016".equals(currency.getAuthorityNumber()) && "003".equals(permissionType)) {

            basicdata = basicdataMapper.getAllByTwoId(id, currency.getManagementOffice());
        } else {

            basicdata = basicdataMapper.getAllByTwoId(id, null);
        }

        return Result.success(basicdata);
    }

    /**
     * @Description: 查询所有二级信息
     * @author zhuliang
     * @date 2020/11/30 21:39
     */
    @Override
    public Result<List<CcmsSmartleasingBasicdata>> getTwoAll(String categoryNumber, String token) {
        List<CcmsSmartleasingBasicdata> twoAll = null;

        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        String tk = null;
        if (null == currency) {

            tk = (String) redisTemplate.opsForValue().get("wechat:" + JWT.decode(token).getClaim("phone").asString());
            if (null == tk || "".equals(tk) || "null".equals(tk)) {

                currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
            } else {

                //查询所有的二级信息
                twoAll = basicdataMapper.getTwoAll(categoryNumber, null, null);
                return Result.success(twoAll);
            }
        }

        //判断权限
        if ("003".equals(currency.getAuthorityNumber()) && "016".equals(categoryNumber) ) {

            //查询所有的二级信息
            twoAll = basicdataMapper.getTwoAll(categoryNumber, currency.getProperty(), null);
        } else if ("016".equals(currency.getAuthorityNumber()) && "016".equals(categoryNumber)) {

            //查询所有的二级信息
            twoAll = basicdataMapper.getTwoAll(categoryNumber, null, currency.getManagementOffice());
        } else {

            //查询所有的二级信息
            twoAll = basicdataMapper.getTwoAll(categoryNumber, null, null);
        }

        return Result.success(twoAll);
    }

    /**
     * @Description: 根据编码查询所有一级信息
     * @author zhuliang
     * @date 2020/12/1 9:58
     */
    @Override
    public Result<List<CcmsSmartleasingBasicdata>> getOneAll(String categoryNumber, String token) {
        List<CcmsSmartleasingBasicdata> oneAll = null;

        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        String tk = null;
        if (null == currency) {

            tk = (String) redisTemplate.opsForValue().get("wechat:" + JWT.decode(token).getClaim("phone").asString());
            if (null == tk || "".equals(tk) || "null".equals(tk)) {

                currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
            } else {

                //查询所有的一级信息
                oneAll = basicdataMapper.getAllByOneId(categoryNumber, null);
                return Result.success(oneAll);
            }
        }

        //判断权限
        if ("003".equals(currency.getAuthorityNumber()) && "003".equals(categoryNumber)) {

            //查询所有的一级信息
            oneAll = basicdataMapper.getAllByOneId(categoryNumber, currency.getProperty());
        } else if ("016".equals(currency.getAuthorityNumber()) && "003".equals(categoryNumber)) {

            //根据二级信息查询一级信息
            oneAll = basicdataMapper.getTwoByOne(categoryNumber, currency.getManagementOffice());
        } else {

            //查询所有的一级信息
            oneAll = basicdataMapper.getAllByOneId(categoryNumber, null);
        }

        return Result.success(oneAll);
    }

    /**
     * @Description: 根据流水号查询开票信息
     * @author zhuliang
     * @date 2020/12/9 10:33
     */

    @Override
    public Result<String> getInvoicingBySerialNumber(String serialNumber) {
        //定义查询信息体Map
        HashMap<String, Object> serialNumberMap = new HashMap<>();

        serialNumberMap.put("identity", basicConfiguration.getIdentity());
        serialNumberMap.put("fpqqlsh", new String[]{serialNumber});

        //将map转换为json字符串
        String json = JSONObject.toJSONString(serialNumberMap) + "";

        //调用接口查询
        String request = HttpUtil.request(basicConfiguration.getNginxUrlPC() + "/queryInvoice", json);

        return Result.success(request);
    }

    /**
     * @Description: 根据订单号查询开票信息
     * @author zhuliang
     * @date 2020/12/9 10:33
     */
    @Override
    public Result<String> byOrderNumber(String orderNumber) {
        //定义查询信息体Map
        HashMap<String, Object> serialNumberMap = new HashMap<>();

        serialNumberMap.put("identity", basicConfiguration.getIdentity());
        serialNumberMap.put("orderno", new String[]{orderNumber});
        serialNumberMap.put("isOfferInvoiceDetail", true);

        //将map转换为json字符串
        String json = JSONObject.toJSONString(serialNumberMap) + "";

        //调用接口查询
        String request = HttpUtil.request(basicConfiguration.getNginxUrlPC() + "/queryInvoice", json);

        return Result.success(request);
    }

    /**
     * @Description: 云丁回调接口
     * @author zhuliang
     * @date 2020/12/23 16:33
     */
    @Override
    public Result getYundingData(YundingCallback yundingCallback) {
        log.info("云丁----》" + yundingCallback);

        //事件发生的时间
        String sEvent = yundingCallback.getEvent();
        Date dtDate = new Date(yundingCallback.getTime());
        String homeId = yundingCallback.getHome_id();
        String sUUID = (yundingCallback.getUuid() == null)? "":yundingCallback.getUuid(); //since uuid not mandatory-from Yunding docs
        String roomId = (yundingCallback.getRoom_id()==null)?"":yundingCallback.getRoom_id(); //as above, it's not mandatory
        JSONObject mapDetail = yundingCallback.getDetail(); //not mandatory as above

//        //根据uuid查询设备的id
        String id = deviceManagementMapper.getDataByYunDing(sUUID);

        //兼容性处理
        if (StringUtils.isBlank(id)) {
            return Result.success();
        }

        //判断报错事件
        String alarm = null;
        if (Arrays.asList(yundingCommonAlarms).contains(sEvent))
            alarm = getCommonAlarm(sEvent,mapDetail);
        else if (Arrays.asList(yundingGatewayAlarms).contains(sEvent))
            alarm = getGatewayAlarm(sEvent,mapDetail);
        else if (Arrays.asList(yundingLockAlarms).contains(sEvent))
            alarm = getLockAlarm(sEvent,mapDetail);
        else if (Arrays.asList(yundingEleMeterAlarms).contains(sEvent))
            alarm = getEleMeterAlarm_updateConsume(sEvent,mapDetail,homeId,roomId,sUUID);
        else if (Arrays.asList(yundingWaterMeterAlarms).contains(sEvent))
            alarm = getWaterMeterAlarm_updateConsume(sEvent,mapDetail,homeId,roomId,dtDate,sUUID); //dtDate only acts as placeholder

        //新增报警信息
        CcmsSmartleasingMessage message = new CcmsSmartleasingMessage();
        message.setPkMessageId(UUID.randomUUID() + "")
                .setFkDeviceManagementId(id)
                .setCreatedBy(0)
                .setCreationDate(new Date())
                .setLastUpdateDate(new Date())
                .setLastUpdatedBy(0)
                .setAlarm(alarm)
                .setAlarmTime(dtDate);

        messageMapper.insert(message);

        return Result.success();
    }

    private String getCommonAlarm(String sEvent,JSONObject mapDetail) {
        String alarm="";
        String deviceType;

        if ("installerSubmit".equals(sEvent)) {
            alarm = "房源设备安装完成";
        } else if ("deviceInstall".equals(sEvent)) {
            deviceType = mapDetail.getString("type");
            alarm= "设备绑定,类型="+ deviceType;
        } else if ("deviceUninstall".equals(sEvent)) {
            deviceType = mapDetail.getString("type");
            alarm= "设备解除绑定,类型="+ deviceType;
        } else if ("lockOfflineAlarm".equals(sEvent)) {
            alarm = "设备离线";
        } else if ("clearLockOfflineAlarm".equals(sEvent)) {
            alarm = "设备解除离线";
        }
        return alarm;
    }

    private String getGatewayAlarm(String sEvent,JSONObject mapDetail) {
        String alarm="";
        if ("centerOfflineAlarm".equals(sEvent)) {
            alarm ="网关离线";
        } else if ("clearCenterOfflineAlarm".equals(sEvent)) {
            alarm ="网关解除离线";
        }
        return alarm;
    }

    private String getLockAlarm(String sEvent,JSONObject mapDetail) {
        String alarm="";
        if ("batteryAlarm".equals(sEvent)) {     //门锁低电量事件
            //获取电量
            Integer battery_level = mapDetail.getInteger("battery_level");

            //报错信息
            alarm = "门锁->低电量提醒:电量=" + battery_level + "%";

        } else if ("clearBatteryAlarm".equals(sEvent)) {  //门锁解除低电量事件
            //获取电量
            Integer battery_level = mapDetail.getInteger("battery_level");

            //报错信息
            alarm = "门锁->解除低电量提醒:电量=" + battery_level + "%";

        } else if ("brokenAlarm".equals(sEvent)) {      //门锁被破坏事件
            //报错信息
            alarm = "门锁被破坏事件->门锁被暴力破坏";

        } else if ("wrongPwdAlarm".equals(sEvent)) {    //密码连续输入错误事件
            //报错信息
            alarm = "密码连续输入错误事件->门锁连续输入错误5次";
        } else if ("lockerOpenAlarm".equals(sEvent)) {
            Integer source = mapDetail.getInteger("source");
            Integer sourceId = mapDetail.getInteger("sourceid");
            String source_name = mapDetail.getString("source_name");
            alarm = "开锁事件,开锁方式=" + source + ";开锁密码id="+sourceId+";开锁密码的名称=" + source_name;

        } else if ("lockOpenHistoryAlarm".equals(sEvent)) {
            String historyLockOpenEvents = mapDetail.getJSONArray("events").toString();
            alarm ="历史开锁事件上传" + historyLockOpenEvents;
        } else if ("batteryAsync".equals(sEvent)) {
            Integer battery = mapDetail.getInteger("battery");
            alarm = "电量更新" + battery;
        } else if ("pwdUpdateLocal".equals(sEvent)) {
            alarm = "密码本地修改,密码id=" + mapDetail.getString("id");
        }
        return alarm;
    }

    private String getEleMeterAlarm_updateConsume(String sEvent, JSONObject mapDetail, String homeId, String roomId, String sUUID) {
        String alarm = "";
        if ("elemeterPowerAsync".equals(sEvent)) {  //电表
            //获取电表的读数和读取时间
            BigDecimal consume_amount = BigDecimal.valueOf(mapDetail.getFloat("consume_amount"));
            Long consume_amount_time = mapDetail.getLong("consume_amount_time");
            Date dtDatetime = new Date(consume_amount_time);

            //写入到数据库
            deviceManagementMapper.updateByYunDing(new Date(), 0, homeId,
                    roomId, consume_amount, dtDatetime, sUUID);
            alarm = "获取电表的读数和读取时间:读数"+consume_amount+",时间="+dtDatetime;
        } else if ("elemeterHistory".equals(sEvent)) {
            String elemeterExceptionHistory = mapDetail.getJSONArray("historys").toString();
            alarm = "电表历史异常记录上传,历史="+elemeterExceptionHistory;
        } else if ("elemeterOvercomeAmount".equals(sEvent)) {
            Float flAmount = mapDetail.getFloat("amount");
            alarm = "电费欠费,金额="+flAmount;
        } else if ("elemeterOvercomeCapacity".equals(sEvent)) {
            Float flCapacity = mapDetail.getFloat("capacity");
            alarm ="电表超功率,超功率="+flCapacity;
        } else if ("elemeterLocalClose".equals(sEvent)) {
            alarm ="电表本地合闸";
        } else if ("elemeterTransError".equals(sEvent)) {
            alarm ="电表通讯错误";
        } else if ("elemeterPowerHisAsync".equals(sEvent)) {
            String elemterPowerHistory = mapDetail.getJSONArray("powers").toString();
            alarm = "电表电量历史记录上传,电量历史="+elemterPowerHistory;
        }

        return alarm;
    }

    private String getWaterMeterAlarm_updateConsume(String sEvent, JSONObject mapDetail, String homeId, String roomId, Date dtDate, String sUUID) {
        String alarm = "";
        if ("watermeterAmountAsync".equals(sEvent)) {    //水表
            //获取水表的读数和读取时间
            BigDecimal amount = BigDecimal.valueOf(mapDetail.getFloat("amount"));

            //写入到数据库
            deviceManagementMapper.updateByYunDing(new Date(), 0, homeId,
                    roomId, amount, dtDate, sUUID); //dtDate only acts as a placeholder,since no consume_time passed in via API
            alarm = "水表读数更新,读数="+amount;

        } else if ("deviceReplace".equals(sEvent)) {
            alarm = "水表采集器替换，设备类型=" + mapDetail.getInteger("type");
        } else if ("waterGatewayOfflineAlarm".equals(sEvent)) {
            alarm = "水表采集器离线";
        } else if ("waterGatewayOnlineAlarm".equals(sEvent)) {
            alarm = "水表采集器在线";
        } else if ("watermeterOvercomeAmount".equals(sEvent)) {
            alarm = "水表超水量,水表最新读数=" + mapDetail.getFloat("amount");
        }
        return alarm;
    }

    /**
     * @Description: 获取二进制中1的bit位
     * @author zhuliang
     * @date 2021/1/5 14:53
     */
//    private List<Integer> getBinaryOnePosition(Integer number) {
//        //定义存放位置的集合
//        List<Integer> index = new ArrayList<>();
//
//        //将数字转换为二进制
//        String indexes = Integer.toBinaryString(number);
//
//        //获取其bit位
//        int k = indexes.length();
//        while (k >= 0) {
//            int ind = indexes.lastIndexOf("1", k);
//            if (ind >= 0) {
//                k = indexes.lastIndexOf("1", k) - 1;
//                index.add(ind);
//            }
//            else {
//                break;
//            }
//        }
//
//        return index;
//    }

    /**
     * @Description: 绿米消息回调接口
     * @author zhuliang
     * @date 2021/1/8 15:20
     */
    @Override
    public Object getGreenRiceData(GreenRiceCallback greenRiceCallback) {

        log.info("绿米----》" + greenRiceCallback);

        //验证服务器
        //写入返回值
        if (StringUtils.isNotBlank(greenRiceCallback.getEchostr())) {
            log.info("绿米验证服务器开始----》" + greenRiceCallback);

            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", 0);
            resultMap.put("result", greenRiceCallback.getEchostr());

            //将map转换为json
            JSONObject jsonObject = new JSONObject(resultMap);

            log.info("绿米验证服务器成功----》" + greenRiceCallback);
            return jsonObject;
        }

        for (JSONObject jsonObject : greenRiceCallback.getData()) {
            String temperatureValue = null;
            String humidityValue = null;
            String pressureValue = null;
            String did = jsonObject.getString("did");        //设备id
            Long time = jsonObject.getLong("time");      //获取的时间戳，毫秒
            String attr = jsonObject.getString("attr");      //设备属性名称
            String value = jsonObject.getString("value");    //读取的值

            if (attr.equals("humidity_value")) {
                humidityValue = value;
            } else if (attr.equals("temperature_value")) {
                temperatureValue = value;
            } else if (attr.equals("pressure_value")) {
                pressureValue = value;
            } else {
                continue;
            }

            deviceManagementMapper.updateByLuMi(new Date(), 0, new Date(time), temperatureValue, humidityValue, pressureValue, did);
        }

        return Result.success();
    }

    /**
     * @Description: 注销登录
     * @author zhuliang
     * @date 2021/1/14 11:50
     */
    @Override
    public Result logout(String token) {
        //得到token密钥
        String signature = JWT.decode(token).getSignature();
        String string = JWT.decode(token).getClaim("phone").asString();
        if (StringUtils.isNotBlank(string)) {
            redisTemplate.delete("ccms:" + string);
        }

        //删除redis内登录信息
        redisTemplate.delete("ccms:" + signature);

        return Result.success();
    }

    /**
     * @Description: 读取指定目录的xlsx文件，生成房间数据
     * @author zhuliang
     * @date 2021/1/25 16:22
     */
    @Override
    public Result addRoomByExcel(String url) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(url));
            XSSFWorkbook book = new XSSFWorkbook(inputStream);
            if (0 >= book.getNumberOfSheets()) {
                log.error("getArrayFromXLSX error: bookIndex={} is to large! ", 0);
                return null;
            }
            XSSFSheet sheet = book.getSheetAt(0);
            int rowNum = sheet.getLastRowNum() + 1;
            int coloumNum = sheet.getRow(0).getPhysicalNumberOfCells();
            String[][] contents = new String[rowNum][coloumNum];
            for (int j = 1; j < rowNum; j++) {
                XSSFRow row = sheet.getRow(j);
                if (row != null) {
                    for (int k = 0; k < row.getLastCellNum(); k++) {
                        contents[j][k] = getXCellFormatValue(row.getCell(k));
                    }
                }
            }
            //遍历二维数据
            for (int i = 1; i < contents.length; i++) {
                //查询楼宇id
                String buildingId = buildingMapper.getIdByBuildingName(contents[i][1]);

                //查询户型id
                String houseTypeId = houseTypeMapper.getIdByName(contents[i][10], buildingId);

                //查询税率模板id
                String taxId = taxRateTemplateMapper.getIdByName(contents[i][3]);

                //查询费用模板id
                String coefficientId = coefficientTemplateMapper.getIdByName(contents[i][2]);

                CcmsSmartleasingRoom room = new CcmsSmartleasingRoom();
                room.setPkRoomId(UUID.randomUUID() + "");
                room.setCreatedBy(0);
                room.setCreationDate(new Date());
                room.setLastUpdateDate(new Date());
                room.setLastUpdatedBy(0);
                room.setRoomName(contents[i][0]);
                room.setFkBuildingId(buildingId);
                room.setFkCoefficientTemplateId(coefficientId);
                room.setFkTaxRateTemplateId(taxId);
                room.setFkHouseTypeId(houseTypeId);
                room.setFkFloorId(contents[i][4]);
                room.setHouseNumber(contents[i][9]);
                room.setHousingAssetsCode(contents[i][11]);
                room.setUnitCoding(contents[i][5]);
                room.setWaterCostCode(contents[i][6]);
                room.setElectricCostCode(contents[i][7]);
                room.setCoalGasCostCode(contents[i][8]);
                room.setFkRoomPurpose(contents[i][12]);
                room.setFkRoomStatusId("ca68415c-1df1-11eb-9143-00ffb95445a5");
                room.setEntrust(new Byte(contents[i][13]));
                room.setEntrustExplain(contents[i][14]);
                room.setHotWaterCostCode(contents[i][15]);
                roomMapper.insert(room);
            }


            return Result.success();
        } catch (FileNotFoundException fe) {
            log.error("getArrayFromXLSX error: FileNotFoundException", fe);
        } catch (IOException ie) {
            log.error("getArrayFromXLSX error: IOException", ie);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error("getArrayFromXLSX close Exception", e);
                }
            }
        }
        return null;
    }

    private String getXCellFormatValue(XSSFCell cell) {
        String cellValue = "";
        if (null != cell) {
            switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_STRING:
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                default:
                    cellValue = " ";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
}
